package com.chinar.funds;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.chinar.funds.until.FundDatabaseHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SendMessageWorker extends Worker {
    private Context context;
    private static final String API_URL = "https://fundgz.1234567.com.cn/js/"; // 基金信息API地址
    private OkHttpClient client;
    private static final String TAG = "SendMessageWorker";

    public SendMessageWorker(@NonNull Context context, @NonNull WorkerParameters params) {
        super(context, params);
        this.context = context;
        this.client = new OkHttpClient();
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "SendMessageWorker 开始执行");
        
        // 获取输入数据，检查是否是测试任务
        String isTest = getInputData().getString("is_test");
        boolean testMode = "true".equals(isTest);
        Log.d(TAG, "是否为测试模式: " + testMode);
        
        // 如果是测试模式，忽略时间检查直接发送消息
        if (testMode) {
            Log.d(TAG, "测试模式下，忽略时间限制");
            FundDatabaseHelper dbHelper = new FundDatabaseHelper(context);
            String messageSwitchStr = dbHelper.getSetting("message_switch", "false");
            Log.d(TAG, "消息开关设置值: " + messageSwitchStr);
            
            // 检查开关状态
            boolean messageSwitch = Boolean.parseBoolean(messageSwitchStr);
            
            // 只有在开关开启的情况下才发送消息
            if (messageSwitch) {
                Log.d(TAG, "消息开关已开启，开始发送基金消息");
                sendFundMessage(dbHelper);
            } else {
                Log.d(TAG, "消息开关已关闭，不发送消息");
            }
        } else {
            // 检查当前时间是否接近目标时间(14:40左右)
            Calendar now = Calendar.getInstance();
            int hour = now.get(Calendar.HOUR_OF_DAY);
            int minute = now.get(Calendar.MINUTE);
            
            Log.d(TAG, "当前时间: " + hour + ":" + minute);

            // 检查是否在目标时间范围内（14:35-14:50）
            if (hour == 14 && minute >= 35 && minute <= 50) {
                Log.d(TAG, "在目标时间范围内，准备发送消息");
                
                FundDatabaseHelper dbHelper = new FundDatabaseHelper(context);
                String messageSwitchStr = dbHelper.getSetting("message_switch", "false");
                Log.d(TAG, "消息开关设置值: " + messageSwitchStr);
                
                // 检查开关状态
                boolean messageSwitch = Boolean.parseBoolean(messageSwitchStr);
                
                // 只有在开关开启的情况下才发送消息
                if (messageSwitch) {
                    Log.d(TAG, "消息开关已开启，开始发送基金消息");
                    // 检查是否为交易日并发送消息
                    sendFundMessage(dbHelper);
                } else {
                    Log.d(TAG, "消息开关已关闭，不发送消息");
                }
            } else {
                Log.d(TAG, "不在目标时间范围内，跳过执行");
            }
        }

        return Result.success();
    }

    private void sendFundMessage(FundDatabaseHelper dbHelper) {
        Log.d(TAG, "开始构建基金消息内容");
        
        // 获取基金列表
        List<String> codes = dbHelper.getAllFundCodes();
        Log.d(TAG, "获取到基金代码数量: " + codes.size());
        
        if (codes.isEmpty()) {
            Log.d(TAG, "基金列表为空，无需发送消息");
            return;
        }

        // 构建消息内容
        StringBuilder message = new StringBuilder();
        message.append("基金估值信息 (").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("):\n\n");

        // 为每个基金代码获取实时信息
        for (String code : codes) {
            Log.d(TAG, "正在获取基金信息: " + code);
            Fund fund = getFundInfo(code);
            if (fund != null) {
                message.append("基金代码: ").append(fund.getCode()).append("\n");
                message.append("基金名称: ").append(fund.getName()).append("\n");
                message.append("基金估值: ").append(fund.getEstimate()).append("\n");
                message.append("单位净值: ").append(fund.getYesterdayNetValue()).append("\n\n");
                Log.d(TAG, "基金信息获取成功: " + fund.getName());
            } else {
                message.append("基金代码: ").append(code).append(" (获取信息失败)\n\n");
                Log.d(TAG, "基金信息获取失败: " + code);
            }
        }

        // 获取企业微信key
        String wechatKey = dbHelper.getSetting("wechat_key", "c5abeaf8-f071-4759-b17e-9b2cfa9ee37c");
        Log.d(TAG, "获取企业微信key完成");

        // 发送消息到企业微信
        Log.d(TAG, "准备发送消息到企业微信");
        Log.d(TAG, "消息内容:\n" + message.toString());
        sendWechatMessage(wechatKey, message.toString());
    }

    /**
     * 实时获取基金信息
     * @param code 基金代码
     * @return Fund对象，包含基金详细信息
     */
    private Fund getFundInfo(String code) {
        final Fund[] result = {null};
        final CountDownLatch latch = new CountDownLatch(1);

        Request request = new Request.Builder()
                .url(API_URL + code + ".js")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取基金信息失败: " + code, e);
                latch.countDown();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonpData = response.body().string();
                    Log.d(TAG, "基金API响应数据: " + jsonpData);
                    int firstParenthesis = jsonpData.indexOf('(');
                    int lastParenthesis = jsonpData.lastIndexOf(')');
                    if (firstParenthesis != -1 && lastParenthesis != -1 && lastParenthesis > firstParenthesis) {
                        String json = jsonpData.substring(firstParenthesis + 1, lastParenthesis);
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            result[0] = new Fund(
                                    jsonObject.getString("fundcode"),
                                    jsonObject.getString("name"),
                                    jsonObject.getString("gsz"),
                                    jsonObject.getString("dwjz")
                            );
                        } catch (JSONException e) {
                            Log.e(TAG, "解析基金JSON数据失败: " + code, e);
                        }
                    } else {
                        Log.e(TAG, "基金数据格式错误: " + code);
                    }
                } else {
                    Log.e(TAG, "基金API响应不成功: " + response.code() + " " + response.message());
                }
                latch.countDown();
            }
        });

        try {
            // 等待异步请求完成，最多等待10秒
            if (!latch.await(10, TimeUnit.SECONDS)) {
                Log.e(TAG, "获取基金信息超时: " + code);
            }
        } catch (InterruptedException e) {
            Log.e(TAG, "获取基金信息被中断: " + code, e);
        }

        return result[0];
    }

    /**
     * 发送消息到企业微信
     * @param wechatKey 企业微信key
     * @param message 消息内容
     */
    private void sendWechatMessage(String wechatKey, String message) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + wechatKey;
        Log.d(TAG, "企业微信发送URL: " + url);
        
        try {
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("msgtype", "text");
            JSONObject content = new JSONObject();
            content.put("content", message);
            jsonBody.put("text", content);
            
            Log.d(TAG, "构建的JSON消息体: " + jsonBody.toString());
            
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(jsonBody.toString(), JSON);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "发送企业微信消息失败", e);
                }
                
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        Log.d(TAG, "企业微信消息发送成功，响应: " + response.body().string());
                    } else {
                        Log.e(TAG, "企业微信消息发送失败: " + response.code() + " " + response.message() + 
                                ", 响应内容: " + response.body().string());
                    }
                    response.close();
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "构建企业微信消息失败", e);
        }
    }
}